<script src="https://maps.googleapis.com/maps/api/js?key=<?php echo $mapConfig['map_key']; ?>&callback=initMap&libraries=places&v=weekly" async></script>
<style>
    #map-container {
        overflow: hidden;
        width: 100%;
        height: 400px;
        margin: 0;
        font-family: "微软雅黑";
    }
</style>
<div class="form-group">
    <label class="col-sm-2 control-label"><?php echo $this->translate('地图'); ?></label>
    <div class="col-sm-10">
        <?php echo $this->formElement($form->get('locationGeoCoding')); $mapLatAndLng = []; if ($this->locationInfo && !empty($this->locationInfo->getLocationGeoCoding())) $mapLatAndLng = explode(',', $this->locationInfo->getLocationGeoCoding()); ?>
        <div style="margin-bottom: 10px;">
            <input type="text" name="searchArea" id="searchArea" class="form-control" placeholder="<?php echo $this->translate('输入需要查询的地点，在下拉列表中选择'); ?>" value="" style="width: 360px;display: unset;">
            <small class="text-blue"><?php echo $this->translate('这里的输入只用来做查询定位具体地点，不会做存储处理。'); ?></small>
            <small class="text-red"><?php echo $this->translate('选择地点后，拖动地图中的红色标识，确定具体位置。'); ?></small>
        </div>

        <div id="map-container"></div>
    </div>
</div>
<script type="text/javascript" lang="ts">
    let map;
    function initMap() {
        const myLatlng = {<?php if (!empty($mapLatAndLng)) echo "lat: $mapLatAndLng[1], lng: $mapLatAndLng[0]"; else echo  'lat:39.89297410910546, lng:116.45855137008361'; ?>};
        map = new google.maps.Map(document.getElementById("map-container"), {
            center: myLatlng,
            mapTypeControl: false,
            streetViewControl:false,
            zoom: <?php if (!empty($mapLatAndLng)) echo 17; else echo 8; ?>
        });
        geocoder = new google.maps.Geocoder();

        const marker = new google.maps.Marker({
            position: myLatlng,
            draggable: true,
            map
        });
        google.maps.event.addListener(marker, "dragend", (mapsMouseEvent) => {
            marker.setVisible(false);
            marker.setPosition(mapsMouseEvent.latLng.toJSON());
            marker.setVisible(true);

            document.getElementById('locationGeoCoding').value = mapsMouseEvent.latLng.toJSON().lng + ',' + mapsMouseEvent.latLng.toJSON().lat;
        });

        const options = {
            fields: ["formatted_address", "geometry", "name"],
            strictBounds: false,
            types: ["establishment"],
        };
        const autocomplete = new google.maps.places.Autocomplete(document.getElementById('searchArea'), options);
        autocomplete.addListener("place_changed", () => {
            marker.setVisible(false);
            const place = autocomplete.getPlace();
            map.setCenter(place.geometry.location);
            map.setZoom(17);
            marker.setPosition(place.geometry.location);
            marker.setVisible(true);

            document.getElementById('locationGeoCoding').value = place.geometry.location.toJSON().lng + ',' + place.geometry.location.toJSON().lat;
        });

        const centerControlDiv = document.createElement("div");
        CenterControl(centerControlDiv, map);
        map.controls[google.maps.ControlPosition.TOP_CENTER].push(centerControlDiv);

        function CenterControl(controlDiv, map) {
            const controlUI = document.createElement("div");

            controlUI.style.backgroundColor = "#00a65a";
            controlUI.style.border = "2px solid #008d4c";
            controlUI.style.borderRadius = "3px";
            controlUI.style.boxShadow = "0 2px 6px rgba(0,0,0,.3)";
            controlUI.style.cursor = "pointer";
            controlUI.style.marginTop = "8px";
            controlUI.style.marginBottom = "22px";
            controlUI.style.textAlign = "center";
            controlUI.title = "";
            controlDiv.appendChild(controlUI);

            // Set CSS for the control interior.
            const controlText = document.createElement("div");

            controlText.style.color = "#fff";
            controlText.style.fontFamily = "Roboto,Arial,sans-serif";
            controlText.style.fontSize = "16px";
            controlText.style.lineHeight = "30px";
            controlText.style.paddingLeft = "5px";
            controlText.style.paddingRight = "5px";
            controlText.innerHTML = "点击填入详细地址";
            controlUI.appendChild(controlText);

            controlUI.addEventListener("click", () => {
                geocoder.geocode({ location: marker.getPosition().toJSON() })
                    .then((response) => {
                        if (response.results[0]) {
                            document.getElementById('locationAddress').value = response.results[0].formatted_address;
                        } else {
                            window.alert("No results found");
                        }
                    })
                    .catch((e) => window.alert("Geocoder failed due to: " + e));
            });
        }
    }
</script>